package ru.urfc.portal.dao.filter;

import java.text.MessageFormat;
import java.util.List;

public class Operator {
	private String pattern;
	
	public static final Operator GREAT_OR_EQUAL = new Operator("this.{0} >= :{1}");
	public static final Operator LESS_OR_EQUAL = new Operator("this.{0} <= :{1}");
	public static final Operator EQUAL = new Operator("this.{0} = :{1}");
	public static final Operator IS_NULL = new Operator("this.{0} IS NULL") {
		public String generate(VariablesHolder variablesHolder, Predicate predicate) {
			return MessageFormat.format(getPattern(), predicate.getPropertyName());
		};
	};
	public static final Operator LIKE_IGNORE_CASE = new Operator("LOWER(this.{0}) LIKE :{1}") {
		protected Object getValue(Predicate predicate) {
			return "%" + predicate.getValue().toString().toLowerCase() + "%";
		};
	};
	public static final Operator IN_LIST = new Operator("this.{0} in ({1})") {
		public String generate(VariablesHolder variablesHolder, Predicate predicate) {
			List<Long> ids = (List<Long>) predicate.getValue();
			if (ids.size() == 0) {
				return "1 = 2";
			}
			StringBuilder values = new StringBuilder("");
			for (Long id: ids) {
				if (values.length() != 0) {
					values.append(", ");
				}
				values.append(":");
				values.append(variablesHolder.put(id));
			}
			return MessageFormat.format(getPattern(), predicate.getPropertyName(), values.toString());
		};
	};

	protected Operator(String pattern) {
		super();
		this.pattern = pattern;
	}
	
	public String getPattern() {
		return pattern;
	}

	public String generate(VariablesHolder variablesHolder, Predicate predicate) {
		return MessageFormat.format(pattern, predicate.getPropertyName(), variablesHolder.put(getValue(predicate)));
	}

	protected Object getValue(Predicate predicate) {
		return predicate.getValue();
	}
	
}
